package com.funtester.seven.day4;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.funtester.seven.day0.Output;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.*;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

public class HttpUtil {

    public static CloseableHttpClient aDefault = HttpClients.createDefault();


    public static void main(String[] args) throws IOException {

//        String url = "https://www.fewords.cn/api/user/msgrecent";
//
//        JSONObject params = new JSONObject();
//        params.put("name", "ff房东afff");
//        params.put("age", 324);
//
//        HttpGet httpGet = getGet(url, params);
//
//        httpGet.addHeader("user", "FunTester");
//
//        String response = getResponse(httpGet);
//
//        System.out.println(response);

//        String url = "http://123.56.99.53:9000/event/api/admin/";
//        JSONObject params = new JSONObject();
//        params.put("username", "admin");
//        params.put("password", base64Encode("123admin"));
//        HttpPost post = getPost(url, params);
//        String response = getResponse(post);
//        System.out.println(response);

        String url = "http://123.56.99.53:9000/event/api/register/";
        JSONObject params = new JSONObject();
        params.put("username", "FunTester");
        params.put("password", "123456789");
        params.put("phone", "13120454212");
        params.put("email", "FunTester@88.com");
        HttpPost post = getPost(url, params);
        post.addHeader("uid", "2");
        post.addHeader("key", "3c312df4f5a85216b50ddcc97b4d344031c02106");
        JSONObject response = getResponse(post);

        System.out.println(response);
        output(response);
    }

    public static void output(JSONObject json) {
        Output.outputJsonStr(json.toString());
    }

    /**
     * 解析响应
     *
     * @param request
     * @return
     */
    public static String getResponse1(HttpRequestBase request) {
        CloseableHttpResponse response = null;
        try {
            response = aDefault.execute(request);
            if (check(response)) {
                return parseResponse(response);
            } else {
                return "出错了";
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            response.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static JSONObject getResponse(HttpRequestBase request) {

        CloseableHttpResponse response = null;
        System.out.println("发送请求" + request.getURI().toString());
        try {
            response = aDefault.execute(request);
            if (check(response)) {
                String s = parseResponse(response);
                return JSON.parseObject(s);
            } else {
                String s = parseResponse(response);
                System.out.println(s);
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            response.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 表单形式
     *
     * @param url
     * @param params
     * @return
     */
    public static HttpPost getPost(String url, JSONObject params) {
        HttpPost httpPost = new HttpPost(url);
        if (params != null && !params.isEmpty()) {
            List<NameValuePair> formparams = new ArrayList<NameValuePair>();
            //遍历JSON
            Set<Map.Entry<String, Object>> entries = params.entrySet();

            for (Map.Entry<String, Object> entry : entries) {
                BasicNameValuePair basicNameValuePair = new BasicNameValuePair(entry.getKey(), entry.getValue().toString());
                formparams.add(basicNameValuePair);
            }

            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
            httpPost.setEntity(entity);
        }
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        return httpPost;
    }

    /**
     * json形式,text
     *
     * @param url
     * @param params
     * @return
     */
    public static HttpPost getPost(String url, String params) {
        HttpPost httpPost = new HttpPost(url);
        if (StringUtils.isNotBlank(params))
            httpPost.setEntity(new StringEntity(params, "UTF-8"));
        httpPost.addHeader("Content-Type", "application/json; charset=" + "UTF-8");
        return httpPost;
    }

    public static HttpPost getJsonPost(String url, JSONObject params) {
        return getPost(url, params.toString());
    }

    /**
     * 获取一个GET请求
     *
     * @param url
     * @param params
     * @return
     */
    public static HttpGet getGet(String url, JSONObject params) {

        String p = changeJsonToArguments(params);

        return new HttpGet(url + p);
    }


    /**
     * 解析响应
     *
     * @param response
     * @return
     */
    public static String parseResponse(CloseableHttpResponse response) {
        HttpEntity entity = response.getEntity();//获取响应实体
        try {
            String s = EntityUtils.toString(entity);//解析响应实体,为String类型
            EntityUtils.consume(entity);//释放资源
            return s;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 验证响应是否成功
     *
     * @param response
     * @return
     */
    public static boolean check(CloseableHttpResponse response) {
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        return statusCode == HttpStatus.SC_OK;
    }


    /**
     * 打印所有headers
     *
     * @param message
     */
    public static void outputHeaders(HttpMessage message) {
        Header[] allHeaders = message.getAllHeaders();
        for (int i = 0; i < allHeaders.length; i++) {
            System.out.println(allHeaders[i]);
        }
    }

    /**
     * 将GET请求参数拼接转码
     *
     * @param ps
     * @return
     */
    public static String changeJsonToArguments(JSONObject ps) {
        String p = "?";
        Set<Map.Entry<String, Object>> entries = ps.entrySet();
        for (Map.Entry<String, Object> entry : entries) {
            String key = entry.getKey();
            String value = entry.getValue().toString();
            p = p + key + "=" + encode(value) + "&";
        }
        return p.substring(0, p.length() - 1);
    }

//    public static String changeJsonToArguments(JSONObject argument) {
//        return argument == null || argument.isEmpty() ? "" : argument.keySet().stream().filter(x -> argument.get(x) != null).map(x -> x.toString() + "=" + encode(argument.getString(x.toString()))).collect(Collectors.joining("&", "?", "")).toString();
//    }

    public static String encode(String str) {
        try {
            return URLEncoder.encode(str, Consts.UTF_8.name());//UTF-8
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String base64Encode(String text) {
        try {
            return new String(Base64.getEncoder().encode(text.getBytes(Consts.UTF_8)));
        } catch (Exception e) {
            return "";
        }
    }

}
